package org.spring.config.server.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spring.config.server.page.table.PageTableHandler;
import org.spring.config.server.page.table.PageTableHandler.CountHandler;
import org.spring.config.server.page.table.PageTableHandler.ListHandler;
import org.spring.config.server.page.table.PageTableRequest;
import org.spring.config.server.page.table.PageTableResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 
 * ClassName: ClentInfoController <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON(可选). <br/>
 * date: 2019年10月14日 上午9:48:32 <br/>
 *
 * @author dengqian
 * @version
 * @since JDK 1.8
 */
@RestController
@RequestMapping(value = "/clentInfo")
public class ClentInfoController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ClentInfoController.class);

    @Autowired
    private DiscoveryClient discoveryClient;
    
    @ResponseBody
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public PageTableResponse list(PageTableRequest request) {
        return new PageTableHandler(new CountHandler() {
            @Override
            public int count(PageTableRequest request) {
                return 10;
            }
        }, new ListHandler() {
            @Override
            public List<ServiceInstance> list(PageTableRequest request) {
                List<ServiceInstance> services = new ArrayList<ServiceInstance>();
                List<String> serviceNames = discoveryClient.getServices();
                for (String serviceName : serviceNames) {
                    List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceName);
                    for (ServiceInstance serviceInstance : serviceInstances) {
                        services.add(serviceInstance);
                    }
                }  
                return services;
            }
        }).handle(request);
    }
   
    @ResponseBody
    @RequestMapping(value = "serviceNames", method = RequestMethod.POST)
    public List<String> serviceNames() {
        List<String> serviceNames = discoveryClient.getServices();
        return serviceNames;

    }
    @ResponseBody
    @RequestMapping(value = "operate", method = RequestMethod.POST)
    public String operate(@RequestBody HashMap<String, String> inmap) {
        LOGGER.info(inmap.toString());
        String op = "";
        int post2get = 0;
        if (inmap.get("operate").equals("1")) {// 暂停
            op = "pause";
        }
        if (inmap.get("operate").equals("2")) {// 挂起
            op = "pause";
        }
        if (inmap.get("operate").equals("3")) {// 恢复
            op = "resume";
        }
        if (inmap.get("operate").equals("4")) {// 刷新
            op = "refresh";
        }
        if (inmap.get("operate").equals("5")) {// 主机性能指标
            op = "metrics";
            post2get = 1;
        }

        String url = "http://" + inmap.get("ip") + ":" + inmap.get("port") + "/" + op;

        return getoperate(url, post2get, "", "");
    }

    private static String getoperate(String url, int post2get, String... str) {

        String bodyAsString = "";
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        try {
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10 * 1000)
                .setConnectTimeout(10 * 1000).setSocketTimeout(10 * 1000).build();
            if (post2get == 1) {
                HttpGet po = new HttpGet(url);

                po.setConfig(requestConfig);
                CloseableHttpResponse response = httpClient.execute(po);
                bodyAsString = EntityUtils.toString(response.getEntity());
                LOGGER.info(bodyAsString.toString());
                return bodyAsString.toString();
            }
            if (post2get == 3) {

                HttpPost po = new HttpPost(url);
                po.addHeader(new BasicHeader("Cookie", "JSESSIONID=" + str[0]));
                po.setConfig(requestConfig);
                String queryCase = "name=admin&password=admin&remember=0";
                StringEntity reqEntity = new StringEntity(queryCase);
                reqEntity.setContentType("application/x-www-form-urlencoded");
                po.setEntity(reqEntity);
                CloseableHttpResponse response = httpClient.execute(po);
                bodyAsString = EntityUtils.toString(response.getEntity());
                LOGGER.info(bodyAsString.toString());
                return bodyAsString;

            }
            if (post2get == 4) {
                HttpGet po = new HttpGet(url);
                po.addHeader(new BasicHeader("Cookie", "JSESSIONID=" + str[0] + ";DISCONF=" + str[1]));
                po.setConfig(requestConfig);
                CloseableHttpResponse response = httpClient.execute(po);
                bodyAsString = EntityUtils.toString(response.getEntity());
                LOGGER.info(bodyAsString.toString());
                return bodyAsString;
            }
            if (post2get == 5) {

                HttpPut po = new HttpPut(url);
                po.addHeader(new BasicHeader("Cookie", "JSESSIONID=" + str[0] + ";DISCONF=" + str[1]));
                po.setConfig(requestConfig);
                String text = "fileContent=" + str[2];
                StringEntity reqEntity = new StringEntity(text);
                reqEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
                po.setEntity(reqEntity);
                CloseableHttpResponse response = httpClient.execute(po);
                bodyAsString = EntityUtils.toString(response.getEntity());
                LOGGER.info(bodyAsString.toString());
                return bodyAsString;
            }
            if (post2get == 6) {

                HttpPost po = new HttpPost(url);
                po.setConfig(requestConfig);
                StringEntity reqEntity = new StringEntity(str[0]);
                reqEntity.setContentType("application/json;charset=utf-8");
                po.setEntity(reqEntity);
                CloseableHttpResponse response = httpClient.execute(po);
                bodyAsString = EntityUtils.toString(response.getEntity());
                LOGGER.info(bodyAsString.toString());
                return bodyAsString;

            } else {
                HttpPost po = new HttpPost(url);
                if (str != null && str.length > 0) {
                    po.addHeader(new BasicHeader("Cookie", "JSESSIONID=" + str[0]));
                }
                StringEntity reqEntity = new StringEntity("");
                reqEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
                po.setEntity(reqEntity);

                po.setConfig(requestConfig);
                CloseableHttpResponse response = httpClient.execute(po);
                bodyAsString = EntityUtils.toString(response.getEntity());
                LOGGER.info(bodyAsString.toString());
                return bodyAsString;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "{}";
    }

  

}
